* Table 3: Characteristics of winners and losers: preference flip algorithm

********************************************************************************
************************** Prepare data ****************************************
********************************************************************************

clear all
use id winner_h2 loser_h2 using "${data_matchings}", clear
merge 1:n id using "${data_students}", keepusing(disadv grossincome ses budapest county_town town village GPA11_3 gender)
		
		
********************************************************************************
************************** Prepare table ***************************************
********************************************************************************

cap file close sumstat
file open sumstat using "${table3}", write replace
file write sumstat "\begin{tabular}{l S[table-number-alignment = center-decimal-marker] S[table-number-alignment = center-decimal-marker] S[table-number-alignment = center-decimal-marker]} \\ \hline\hline" _n
file write sumstat " & \multicolumn{1}{c}{Winners} & \multicolumn{1}{c}{Losers} & \multicolumn{1}{c}{p-values: (1)=(2)} \\ " _n
file write sumstat " & \multicolumn{1}{c}{(1)} & \multicolumn{1}{c}{(2)} & \multicolumn{1}{c}{(3)}  \\ \hline" _n

foreach var of varlist disadv grossincome ses budapest county_town town ///
		village GPA11_3 gender {

	local lab_var: variable label `var'
	
	* Winners
	qui sum `var' if winner_h2 == 1
	local mean_win_`var': display %4.3f r(mean)

	* Losers
	qui sum `var' if loser_h2 == 1
	local mean_lose_`var': display %4.3f r(mean)
	
	* Winners vs. losers
	qui reg `var' winner_h2 if winner_h2 == 1 | loser_h2 == 1, r
	local diff1_`var'_p: display %4.3f (2 * ttail(e(df_r), abs(_b[winner_h2]/_se[winner_h2])))
	
	file write sumstat " `lab_var' & `mean_win_`var'' & `mean_lose_`var'' & `diff1_`var'_p' \\ " _n
}

qui: count if winner_h2 == 1 
local winner_count: display %12.0fc r(N)

qui: count if loser_h2 == 1 
local loser_count: display %12.0fc r(N)

qui: count if winner_h2 == 1 | loser_h2 == 1
local sample_count: display %12.0fc r(N)

file write sumstat "\hline Number of applicants & \multicolumn{1}{c}{`winner_count'} & \multicolumn{1}{c}{`loser_count'} & \multicolumn{1}{c}{`sample_count'} \\ \hline\hline " _n 
file write sumstat "\multicolumn{4}{p{14cm}}{{\it Notes}: The table reports the mean values of characteristics of winners and losers from changing the benchmark \SRDA to the preference flip algorithm. Column (3) presents p-values for the equality of mean characteristics of winners and losers.}"
file close sumstat
